<template>
  <div>
    <div class="form-project-product-build">
      <biz-remote-select ref="projectProductRef" :field="field" :is-show-select="true" :value="projectProductValue" :remote-method="remoteProduct" @input="updateProduct" :placeholder="$t('task.tip.searchTip', { name: $t('common.base.product') })" multiple :computed-width-keys="['name', 'serialNumber']" :keyword-length-limit="true" cleared>
        <div class="product-template-option" slot="option" slot-scope="{ option }">
          <h3>{{ option.name }}</h3>
          <p>
            <span>
              <label>{{ $t('common.form.type.productNo') }}：</label>
              <span>{{ option.serialNumber }}</span>
            </span>
            <span>
              <label>{{ $t('common.base.productType') }}：</label>
              <span>{{ option.type }}</span>
            </span>
            <span>
              <label>{{ $t('common.base.customer') }}：</label>
              <span v-if="option.customer && option.customer.id">{{ option.customer.name }}</span>
              <span class="customer-unbind-name" v-else>{{ $t('common.base.notContact') }}</span>
            </span>
          </p>
        </div>
      </biz-remote-select>
      <el-button type="plain-third" class="ml_12" v-if="createdProductPermission" @click="handleClickCreate">{{ $t('common.base.create') }}</el-button>
    </div>

    <!-- start 新建产品弹窗 -->
    <base-modal :title="$t('task.edit.createSth', { name: $t('common.base.product') })" :show.sync="addProductDialog" class="add-dialog-container" width="800px" @cancel="handleClickCancel">
      <div id="createProductView"></div>
      <div class="dialog-footer" slot="footer">
        <el-button @click="handleClickCancel">{{ $t('common.base.close') }}</el-button>
        <el-button type="primary" @click="submitProduct">{{ $t('common.base.save') }}</el-button>
      </div>
    </base-modal>
    <!-- end 新建产品弹窗 -->
  </div>
</template>
<script>
import { getCreateProductData } from '@src/api/TaskApi.ts';

import methods from '@src/modules/task/edit/components/TaskEditForm/methods';
import _ from 'lodash';

export default {
  name: 'form-project-product',
  props: {
    field: {
      type: Object,
      default: () => ({}),
    },
    value: {
      type: Array,
      default: () => [],
    },
    customer: {
      type: Array,
      default: () => [],
    },
    address: {
      type: Array,
      default: () => [],
    },
    linkman: {
      type: Array,
      default: () => [],
    }
  },
  data() {
    return {
      projectProductValue: [],
      productInitData: {},
      addProductDialog: false,
      // productFormView: {},
    };
  },
  watch: {
    value: {
      handler(newValue) {
        if (!newValue) return;

        this.projectProductValue = _.cloneDeep(newValue);
      },
      immediate: true,
    },
  },
  computed: {
    // 客户信息
    customerInfo() {
      return this.customer[0] || {};
    },
    // 客户id
    customerId() {
      return this.customerInfo?.id || '';
    },
    // 联系人id
    linkmanId() {
      return this.linkman?.[0]?.id || ''
    },
    // 客户地址id
    customerAddressId() {
      return this.address?.[0]?.id || ''
    },
    // 新建产品的权限
    createdProductPermission() {
      let initData = JSON.parse(sessionStorage.getItem('_init_data'));

      return initData?.auths?.PRODUCT_CREATE > 0;
    },
    productFormDom() {
      return this?.productFormView?.$refs?.ProductCreateView || {};
    },
  },
  methods: {
    ...methods.search,
    ...methods.render,
    /**
     * @description 获取产品数据
     */
    async fetchProductData() {
      const ret = await getCreateProductData();

      const { status, message, data } = ret;

      let isSuccess = status == 0;
      if (isSuccess) {
        this.productInitData = data;
        this.productFormView = this.renderProductForm(data);
      } else {
        this.$platform.alert(message);
      }
      return data;
    },
    // 搜索产品
    async remoteProduct(params) {
      params.customerId = this.customerId;

      return this.searchProduct(params);
    },
    // 更新产品
    updateProduct(newVal) {
      this.$emit('updateProduct', newVal);
    },
    // 获取当前客户下面的产品
    searchCurrentCustomerProduct() {
      this.$nextTick(() => {
        this.productFormDom.outsideSearch();
      });
    },
    /**
     * @description 打开产品弹窗处理
     */
    async openProductDialogHandler() {
      try {
        let isHaveProductInitData = Object.keys(this.productInitData) > 0;
        if (!isHaveProductInitData) {
          await this.fetchProductData();
        }
        this.productFormDom.init = true;
        this.addProductDialog = true;
      } catch (error) {
        console.warn('openProductDialogHandler -> error', error);
      }
    },
    // 添加产品 提交
    submitProduct() {
      let customer = {
        id: this.customerId,
        // 这两个参数需要传不然新建的产品下面的联系人和地址为空。
        linkman: {id: this.linkmanId},
        address: {id: this.customerAddressId}
      };
      this.productFormDom.submit(customer, data => {
        let productArr = this.value.length ? _.cloneDeep(this.value) : [];
        productArr.push({
          value: data.productId,
          label: data.productName,
          id: data.productId,
          name: data.productName,
          customerId: customer.id,
          ...data,
        });

        this.updateProduct(productArr);

        this.$refs.projectProductRef.outsideSearch('', {
          customerId: customer.id || '',
        });

        this.addProductDialog = false;
      });
    },
    // 取消
    handleClickCancel() {
      this.productFormDom.initFormData();
      this.productFormDom.init = false;
      this.addProductDialog = false;
    },
    // 新建
    handleClickCreate() {
      if (!this.customerId.length) {
        return this.$message.warning(this.$t('common.form.tip.chooseBeforeTips', { module: this.$t('common.base.customer') }));
      }
      this.openProductDialogHandler();
    },
  },
};
</script>
<style lang="scss" scoped>
@import '@src/component/form/components/FormProjectCustomer/remoteSelect.scss';
.form-project-product-build {
  display: flex;
  flex-flow: row nowrap;
}
</style>